/*
clsquare - closed loop simulation system
Copyright (c) 2004, Neuroinformatics Group, Prof. Dr. Martin Riedmiller,
University of Osnabrueck

Author: Martin Riedmiller

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
   * Neither the name of the <ORGANIZATION> nor the names of its
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE. 
*/

#include <stdio.h>
#include <sys/time.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <iomanip>


#include "valueparser.h"
#include "output.h"
#include "global.h"

void Output::print_observation(std::ostream& _out, const double* _observation) 
{
  for (unsigned int i=0; i<reduce_observation_ids.size(); i++)
    _out << std::setw(outp_width) << std::setprecision(outp_prec) << _observation[reduce_observation_ids[i]] << "  ";
}

void Output::print_action(std::ostream& _out, const double* _action) 
{
  for (unsigned int i=0; i<reduce_action_ids.size(); i++)
    _out << std::setw(outp_width) << std::setprecision(outp_prec) << _action[reduce_action_ids[i]] << "  ";
}

void Output::print_state(std::ostream& _out, const double* _state) 
{
  for (unsigned int i=0; i<reduce_state_ids.size(); i++)
    _out << std::setw(outp_width) << std::setprecision(outp_prec) << _state[reduce_state_ids[i]] << "  ";
}

void Output::print_reference_input(std::ostream& _out, const double* _reference_input) 
{
  for (unsigned int i=0; i<reduce_reference_input_ids.size(); i++)
    _out << std::setw(outp_width) << std::setprecision(outp_prec) << _reference_input[reduce_reference_input_ids[i]] << "  ";
}

void Output::print_reward(std::ostream& _out, const double reward)
{
  _out << std::setw(outp_width) << std::setprecision(outp_prec) << reward << "  ";
}

void Output::print_cycle_info(std::ostream& _out, long int cycle, double episode_time, double total_time) {
  timeval tval;
  gettimeofday(&tval,NULL);
  double rtimetotal = ((tval.tv_sec - start_tval.tv_sec) * 1000.+(tval.tv_usec - start_tval.tv_usec) / 1000.) / 1000.;
  _out << std::setw(outp_width) << std::setprecision(outp_prec)<< cycle << " ";
  _out << std::setw(outp_width) << std::setprecision(outp_prec)<< episode_time << " ";
  _out << std::setw(outp_width) << std::setprecision(outp_prec)<< total_time << " ";
  _out << std::setw(outp_width) << std::setprecision(outp_prec)<< rtimetotal << " ";
  _out << " : ";
}

void Output::print_header(std::ostream& _out)
{
  _out << "#";

  _out << "cycleid ";
  _out << "episode_time ";
  _out << "total_time ";
  _out << "real_total_time ";
  _out << " : ";

  switch( output_mode ) {
  case 0:
    _out << "observation(t-1)[";
    for (unsigned int i=0; i<reduce_observation_ids.size(); i++) _out << reduce_observation_ids[i] << " ";
    _out << "] ";
    _out << " | ";
    _out << "action(t-1)[";
    for (unsigned int i=0; i<reduce_action_ids.size(); i++) _out << reduce_action_ids[i] << " ";
    _out << "] ";
    _out << " | ";
    _out << "observation(t)[";
    for (unsigned int i=0; i<reduce_observation_ids.size(); i++) _out << reduce_observation_ids[i] << " ";
    _out << "] ";
    break;
  case 1:
     _out << "observation[";
    for (unsigned int i=0; i<reduce_observation_ids.size(); i++) _out << reduce_observation_ids[i] << " ";
    _out << "] ";
    _out << " | ";
    _out << "action[";
    for (unsigned int i=0; i<reduce_action_ids.size(); i++) _out << reduce_action_ids[i] << " ";
    _out << "] ";
    if (reduce_state_ids.size()>0) {
      _out << " | state[ ";
      for (unsigned int i=0; i<reduce_state_ids.size(); i++) _out << reduce_state_ids[i] << " ";
      _out << "] ";
    }
    if (reduce_reference_input_ids.size()>0) {
      _out << " | reference_input[ ";  
      for (unsigned int i=0; i<reduce_reference_input_ids.size(); i++) _out << reduce_reference_input_ids[i] << " ";
      _out << "] ";
    }
    break;
  };
  _out << "\n";
}

void Output::print_episode_header(std::ostream& _out, long int _sequence)
{
  _out << "\n\n# Started sequence No. " << _sequence << "\n";
}


// write xux information
void Output::write_om0(std::ostream& _out, const double* _prev_observation, const double* _prev_action,  const double _prev_reward, const double* _observation)
{ 
  print_observation( _out , _prev_observation );
  _out << " | ";
  print_action( _out , _prev_action );
  _out << " | "; 
  print_reward(_out, _prev_reward);
  _out << " | ";
  print_observation( _out , _observation );
  _out << "\n";
}

// write all information (dependend on parameters)
void Output::write_om1(std::ostream& _out, const double* _state, const double* _observation, const double* _action, const double reward, const double* _reference_input){
  print_observation( _out , _observation );
  _out << " | ";
  print_action( _out , _action );
  _out << " | ";
  print_reward(_out, reward);
  if (reduce_state_ids.size()>0) {
    _out << " | ";
    print_state( _out , _state );
  }
  if (reduce_reference_input_ids.size()>0) {
    _out << " | ";  
    print_reference_input( _out , _reference_input );
  }
  _out << "\n";
}




/*****************************************************************
 * Output
 *****************************************************************/

bool Output::notify(const double *state, const double *observation, const double *reference_input, 
		    const double *action, const double reward, const long cycle, const long episode,
		    const double total_time, const double episode_time, const long total_num_of_cycles){

  if(output_mode <0)
    return true;

  if(cycle == 1 && episode == 1) print_header(*out);
  if(cycle == 1) print_episode_header(*out, episode);
  
  if(output_mode == 0) {
    if (cycle>1) {
      print_cycle_info(*out, cycle, episode_time, total_time);
      write_om0(*out, prev_observation,  prev_action, reward, observation);
    }
  } else if(output_mode == 1) {
    print_cycle_info(*out, cycle, episode_time, total_time);
    write_om1(*out, state, observation, action, reward, reference_input);
  } else {
    EOUT("Unknown output mode " << output_mode);
    return false;
  }
  
  *out << std::flush;

  // store information
  for(int i=0;i<observation_dim;i++)
    prev_observation[i]=observation[i];
  for(int i=0;i<action_dim;i++)
    prev_action[i]=action[i];
  prev_reward = reward;
  
  return true;
}

bool Output::deinit(){
  if (out!=0) {*out<< std::flush;  delete out;}
  delete[] prev_observation;
  delete[] prev_action;
  return true;
}

bool Output::init(int _state_dim, int _observation_dim, int _action_dim, int _reference_input_dim, double _delta_t, const char *fname){
  // values
  state_dim      = _state_dim;
  action_dim           = _action_dim;
  observation_dim      = _observation_dim;
  reference_input_dim  = _reference_input_dim;
  delta_t              = _delta_t; 

  //defaults 
  out                  = 0;
  sprintf(ProtFName,"%s","default.prot");
  output_mode          = -1; // no output
  outp_width           = 10;
  outp_prec            = 5;
  prev_observation     = new double[observation_dim];
  prev_action          = new double[action_dim];

  reduce_state_ids.clear();
  reduce_observation_ids.clear();
  reduce_action_ids.clear();
  reduce_reference_input_ids.clear();
  for (int i=0; i<observation_dim; i++) reduce_observation_ids.push_back(i);    // default: all observation dims written
  for (int i=0; i<action_dim; i++) reduce_action_ids.push_back(i);         // default: all action dims written
  // default: write no state and reference_input information

  read_options(fname);

  if(output_mode >=0) {
    out = new ofstream(ProtFName);
    if (!out || !*out) {
      EOUT("Can't open file: (" << ProtFName << ")!");
      return false;
    }
  }
  
  gettimeofday(&start_tval,NULL);
  
  return true;
}

bool Output::read_options(const char * fname) 
{
  char paramstr[MAX_STR_LEN];

  if(fname == 0)
    return true;

  ValueParser vp(fname,"Output");

  if(vp.get("output_mode",paramstr,MAX_STR_LEN)>=0){
    if(strcmp(paramstr,"none")== 0)
      output_mode = -1;
    else if(strcmp(paramstr,"standard")== 0)
      output_mode = 1;
    else if(strcmp(paramstr,"xux")== 0)
      output_mode = 0;
    else
      EOUT("Unknown input mode: (" << paramstr <<") using default (standard).");
    // default: -1 (none)
  }

  vp.get("output_file",ProtFName,MAX_STR_LEN);
  
  int tmp[200];
  int n;
  n=vp.get("observation_ids" , tmp, 200);
  if(n >= 0){
    reduce_observation_ids.clear();
    for(int i=0; i<n;i++) {
      if (tmp[i] >= observation_dim || tmp[i] < 0) {
	EOUT("observation_ids " << tmp[i] << " out ouf bounds!");
	return false;
      }
      reduce_observation_ids.push_back(tmp[i]);
    }
  }
  n=vp.get("action_ids" , tmp, 200);
  if(n >= 0){
    reduce_action_ids.clear();
    for(int i=0; i<n;i++) {
      if (tmp[i] >= action_dim || tmp[i] < 0) {
	EOUT("action_ids " << tmp[i] << " out ouf bounds!");
	return false;
      }
      reduce_action_ids.push_back(tmp[i]);
    }
  }
  n=vp.get("state_ids" , tmp, 200);
  if(n >= 0){
    reduce_state_ids.clear();
    for(int i=0; i<n;i++) {
      if (tmp[i] >= state_dim || tmp[i] < 0) {
	EOUT("state_ids " << tmp[i] << " out ouf bounds!");
	return false;
      }
      reduce_state_ids.push_back(tmp[i]);
    }
  }
  n=vp.get("reference_input_ids" , tmp, 200);
  if(n >= 0){
    reduce_reference_input_ids.clear();
    for(int i=0; i<n;i++) {
      if (tmp[i] >= reference_input_dim || tmp[i] < 0) {
	EOUT("reference_input_ids " << tmp[i] << " out ouf bounds!");
	return false;
      }
      reduce_reference_input_ids.push_back(tmp[i]);
    }
  }
  
  return true;
}


